<template>
  <scroll-view class="orders" enable-back-to-top scroll-y>
    <view v-for="order in orderList" :key="order.id" class="card">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.createtime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ order.orderstatus }}</text>
      </view>
      <!-- 商品信息，点击商品跳转到订单详情，不是商品详情 -->
      <view class="orderNumber" @tap="copyOrderId(order.new_orderid)">订单号：{{ order.new_orderid }}</view>
      <view v-for="item in order.meal_list" :key="item.id">
        <view class="goods">
          <view class="cover">
            <image :src="item.picture" class="image" mode="aspectFit"></image>
          </view>
          <view class="meta">
            <view class="name ellipsis">{{ item.name }}</view>
            <view class="type">{{ item.mealdesc }}</view>
          </view>
        </view>
      </view>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount">
          <text class="symbol">¥</text>
          {{ order.finallprice }}
        </text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="order.orderstatus === OrderState.DaiFuKuan">
          <view class="button primary" @tap="onOrderPay(order.id as any)">去支付</view>
          <view class="button" @click="handleDeleteClick(order.id)">删除</view>
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }" class="loading-text">
      {{ '没有更多数据~' }}
    </view>
  </scroll-view>
</template>
<script lang="ts" setup>
  import {
    deleteOrderByOrderId,
    getOrderList,
    getPaymentDataAPI,
    putOrderByID,
  } from '@/services/order'
  import { OrderState } from '@/services/constants'
  import type { OrderCreateParams } from '@/types/order'
  import { onMounted, ref } from 'vue'

  // 获取屏幕边界到安全区域距离
  const { safeAreaInsets } = uni.getSystemInfoSync()

  // 定义 porps
  const props = defineProps<{
    orderState : string
  }>()

  // 请求参数
  const orderstatus = props.orderState
  // 获取订单信息
  const orderList = ref<OrderCreateParams[]>([])
  const getMemberOrderData = async () => {
    const res = await getOrderList(orderstatus)
    // 数组追加
    orderList.value = res.result
  }

  // 订单支付
  const onOrderPay = async (orderId : string) => {
    const res = await getPaymentDataAPI(orderId)
    //发起支付
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: res.result.orderInfo,
      timeStamp: res.result.timeStamp.toString(),
      nonceStr: res.result.nonceStr,
      package: res.result.package,
      signType: 'RSA',
      paySign: res.result.paySign,
      async success(res) {
        //更新订单状态为待送达
        await putOrderByID(orderId)
        // 关闭当前页，再跳转支付结果页
        uni.$emit('closeCart')
        uni.$emit('refreshMealList')
        await uni.redirectTo({ url: `/pagesOrder/payment/payment?order_id=${orderId}` })
        console.log('success:' + JSON.stringify(res))
      },
      fail: function (err) {
        //提醒支付异常
        // 成功提示
        uni.showToast({
          title: '支付异常',
          duration: 1000,
          success: () => {
            setTimeout(() => {
              //查询订单有效性
              //deletetMemberOrderPreData()
              // 关闭当前清单，并跳转到首页
              uni.$emit('closeCart')
              uni.$emit('refreshMealList')
            }, 1000)
          },
        })
        console.log('fail:' + JSON.stringify(err))
      },
    })
  }
  onMounted(() => {
    getMemberOrderData()
  })

  function copyOrderId(id : any) {
    // 使用uni.setClipboardData将订单号复制到剪贴板
    uni.setClipboardData({
      data: id,
      success: () => {
        // 成功回调
        console.log('复制成功');
        uni.showToast({
          title: '复制成功',
          icon: 'success'
        });
      },
      fail: (err) => {
        // 失败回调
        console.error('复制失败', err);
        uni.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  }



  function handleDeleteClick(orderId : any) {
    uni.showModal({
      title: '是否删除订单？',
      showCancel: true,
      async success({ confirm }) {
        if (confirm) {
          const { msg } = await deleteOrderByOrderId(orderId)
          await uni.showToast({
            title: msg,
          })
          await getMemberOrderData()
        }
      },
    })
  }
</script>
<style lang="scss">
  // 订单列表
  .orders {
    .card {
      min-height: 100rpx;
      padding: 20rpx;
      margin: 20rpx 20rpx 0;
      border-radius: 10rpx;
      background-color: #fff;

      &:last-child {
        padding-bottom: 40rpx;
      }
    }

    .orderNumber {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 8rpx;
    }

    .status {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 28rpx;
      color: #999;
      margin-bottom: 5rpx;

      .date {
        color: #666;
        flex: 1;
      }

      .primary {
        color: #ff9240;
      }

      .icon-delete {
        line-height: 1;
        margin-left: 10rpx;
        padding-left: 10rpx;
        border-left: 1rpx solid #e3e3e3;
      }
    }

    .goods {
      display: flex;
      margin-bottom: 20rpx;

      .cover {
        width: 170rpx;
        height: 170rpx;
        margin-right: 20rpx;
        border-radius: 10rpx;
        overflow: hidden;
        position: relative;

        .image {
          width: 170rpx;
          height: 170rpx;
        }
      }

      .quantity {
        position: absolute;
        bottom: 0;
        right: 0;
        line-height: 1;
        padding: 6rpx 4rpx 6rpx 8rpx;
        font-size: 24rpx;
        color: #fff;
        border-radius: 10rpx 0 0 0;
        background-color: rgba(0, 0, 0, 0.6);
      }

      .meta {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      .name {
        height: 80rpx;
        font-size: 26rpx;
        color: #444;
      }

      .type {
        line-height: 1.8;
        padding: 0 15rpx;
        margin-top: 10rpx;
        font-size: 24rpx;
        align-self: flex-start;
        border-radius: 4rpx;
        color: #888;
        background-color: #f7f7f8;
      }

      .more {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22rpx;
        color: #333;
      }
    }

    .payment {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      line-height: 1;
      padding: 20rpx 0;
      text-align: right;
      color: #999;
      font-size: 28rpx;
      border-bottom: 1rpx solid #eee;

      .quantity {
        font-size: 24rpx;
        margin-right: 16rpx;
      }

      .amount {
        color: #444;
        margin-left: 6rpx;
      }

      .symbol {
        font-size: 20rpx;
      }
    }

    .action {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-top: 20rpx;

      .button {
        width: 180rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 20rpx;
        border-radius: 60rpx;
        border: 1rpx solid #ccc;
        font-size: 26rpx;
        color: #444;
      }

      .secondary {
        color: #27ba9b;
        border-color: #27ba9b;
      }

      .primary {
        color: #fff;
        background-color: #27ba9b;
        border-color: #27ba9b;
      }
    }

    .loading-text {
      text-align: center;
      font-size: 28rpx;
      color: #666;
      padding: 20rpx 0;
    }
  }
</style>
